<template>
	<el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
		class="demo-ruleForm" :size="formSize" status-icon>
		<el-form-item label="菜单名称" prop="MenuName">
			<el-input v-model="ruleForm.MenuName" />
		</el-form-item>
		<el-form-item label="路径" prop="MenuUrl">
			<el-input v-model="ruleForm.MenuUrl" />
		</el-form-item>
		<el-form-item label="图标" prop="MenuIcon">
			<el-input v-model="ruleForm.MenuIcon" />
		</el-form-item>
		<ElFormItem label="父级菜单">
		    <el-select v-model="ruleForm.pid" placeholder="Select" style="width: 100%">
		        <el-option :value="0" label="无父级菜单" :key="0" ></el-option>
		        <el-option
		        v-for="item in ruleForm.onelist"
		        :key="item.Id"
		        :label="item.MenuName"
		        :value="item.Id"
		        />
		    </el-select>
		</ElFormItem>
	
		
		<el-form-item>
			<el-button type="primary" @click="submitForm(ruleFormRef)">
				保存
			</el-button>
			<el-button @click="resetForm(ruleFormRef)">重置</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
	import { reactive, ref,onMounted } from 'vue'
	import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
	import { ElNotification } from 'element-plus'

	import menuapi from "@/api/menuapi"

	const emit = defineEmits(['onSave'])

	interface RuleForm {
		MenuName : string
		MenuUrl : string
		MenuIcon : string
		pid:number
	}

	const formSize = ref<ComponentSize>('default')
	const ruleFormRef = ref<FormInstance>()
	const ruleForm = reactive<RuleForm>({
		MenuName : '',
		MenuUrl : '',
		MenuIcon : '',
		pid:0,
		
		 onelist: null as any
	})
		
	const getmenuone = () =>{
	    menuapi.getone().then(res=>{
			console.log("mmm=",res.data)
	        ruleForm.onelist = res.data
	    }).catch(err=>{
	        console.log(err)
	    })
	}
		onMounted(()=>{
		    getmenuone();
		})
		
	const rules = reactive<FormRules<RuleForm>>({
		 MenuName: [
			{ required: true, message: '请输入角色名称', trigger: 'blur' },
			
		],		
		
	})

	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				menuapi.Add(ruleForm).then(res => {
					if (res.code == 1) {
						ElNotification({
							title: 'Success',
							message: '添加成功',
							type: 'success',
							duration: 800,		
						})
							emit("onSave", true)
					} else {
						ElNotification({
							title: 'Error',
							message: '失败',
							type: 'Error',
							duration: 800,
						})
					}
				}).catch(err => {
					ElNotification({
						title: 'Error',
						message: '失败',
						type: 'Error',
						duration: 800,
					})
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}
</script>